package com.yxt.qmgf.snake.ctrl;

import cn.hutool.extra.spring.SpringUtil;
import com.almasb.fxgl.app.GameController;
import com.yxt.qmgf.common.ImageSrc;
import com.yxt.qmgf.shop.ctrl.ShopController;
import com.yxt.qmgf.snake.constant.Const;
import com.yxt.qmgf.snake.constant.Direction;
import com.yxt.qmgf.snake.task.MoveTask;
import com.yxt.qmgf.snake.view.SnakePane;
import com.yxt.qmgf.snake.view.SnakeRoleWindow;
import com.yxt.qmgf.snake.vo.ScoreVO;
import com.yxt.qmgf.snake.vo.SnakeCell;
import com.yxt.qmgf.userinfo.dao.UserInfoDao;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.stage.WindowEvent;

import java.io.IOException;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;

@FXMLController
public class snakeInfoController {

    private UserInfoVO vo;

    private Stage stage;
    private Integer speed;

    private Double scorev;
    @FXML
    public Button backButton;

    private Integer score;

    public static int current_direction = Direction.R;
    private volatile static boolean isRequestClose = false;

    DecimalFormat df = new DecimalFormat("#.0");

    //贪吃蛇的logo
    Image icon = new Image(ImageSrc.snake_logo_path);


    // 显示难度选择对话框
    @FXML
    public void showDifficultyDialog(ActionEvent event) {
        // 创建难度选择对话框
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        Dialog<ButtonType> dialog = new Dialog<>();
        dialog.setTitle("选择难度");
        dialog.setHeaderText("请选择游戏难度");
        alert.setContentText("选择难度后开始游戏");


        // 创建单选按钮组
        ToggleGroup group = new ToggleGroup();
        RadioButton firstButton = new RadioButton("简单");
        RadioButton mediumButton = new RadioButton("正常");
        RadioButton hardButton = new RadioButton("困难");
        RadioButton VhardButton = new RadioButton("极难");
        RadioButton RandomButton = new RadioButton("随机（50-200之间）");

        Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();

        stage.getIcons().add(icon);


        firstButton.setToggleGroup(group);
        mediumButton.setToggleGroup(group);
        hardButton.setToggleGroup(group);
        VhardButton.setToggleGroup(group);
        RandomButton.setToggleGroup(group);
        // 将单选按钮添加到布局中
        VBox vbox = new VBox(10, firstButton, mediumButton, hardButton,VhardButton,RandomButton);
        dialog.getDialogPane().setContent(vbox);

        // 添加确认和取消按钮
        ButtonType confirmButton = new ButtonType("确认", ButtonBar.ButtonData.OK_DONE);
        ButtonType cancelButton = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
        dialog.getDialogPane().getButtonTypes().addAll(confirmButton, cancelButton);

        // 显示对话框并等待用户选择
        Optional<ButtonType> result = dialog.showAndWait();
        if (result.isPresent() && result.get() == confirmButton) {
            if (firstButton.isSelected()) {
                speed = 300; // 简单难度，速度较慢
                scorev = 1.0;
            } else if (mediumButton.isSelected()) {
                speed = 150; // 中等难度，默认速度
                scorev = 1.5;
            } else if (hardButton.isSelected()) {
                speed = 100; // 困难难度，速度较快
                scorev = 2.0;
            } else if (VhardButton.isSelected()){
                speed = 70; //地狱难度，速度非常快
                scorev = 3.5;
            } else if (RandomButton.isSelected()){
                Random random = new Random();
                speed = random.nextInt(151) + 50; // 50 + (0 到 150 的随机值)
                scorev = 0.7+1.8*random.nextDouble();
            }
            startGameWithDifficulty(speed,scorev);
        }

    }

    // 启动游戏并设置速度
    private void startGameWithDifficulty(int speed , double scorev) {
        Stage primaryStage = new Stage();
        primaryStage.setTitle("贪吃蛇大作战");
        SnakePane pane = new SnakePane();
        pane.setSpeed(speed); // 设置初始速度
        pane.setScorv(scorev);

        pane.drawCell();
        action(primaryStage, pane);

        Scene scene = new Scene(pane, 850, 800);
        scene.setOnKeyPressed(new SnakeActionController());
        //logo添加
        primaryStage.getIcons().add(icon);
        primaryStage.setScene(scene);
        primaryStage.show();
    }



    // 游戏规则
    @FXML
    private void role() {
        SnakeRoleWindow srw = new SnakeRoleWindow();
        Stage SnakeRoleWindowStage = new Stage();
        srw.start(SnakeRoleWindowStage);
    }

    // 积分获取记录
    @FXML
    private void jifen() {
        // 加载积分记录
        List<ScoreVO> scores = ScoreManager.loadScores();

        // 创建新的窗口或对话框显示积分记录
        Stage stage = new Stage();
        stage.setTitle("积分获取记录");

        // 创建表格视图
        TableView<ScoreVO> tableView = new TableView<>();
        tableView.setItems(FXCollections.observableArrayList(scores)); // 绑定数据

        // 创建表格列
        TableColumn<ScoreVO, Integer> scoreColumn = new TableColumn<>("游戏积分");
        scoreColumn.setCellValueFactory(new PropertyValueFactory<>("score"));

        TableColumn<ScoreVO, Integer> scorevColumn = new TableColumn<>("转化积分");
        scorevColumn.setCellValueFactory(new PropertyValueFactory<>("scoreV"));

        TableColumn<ScoreVO, Integer> scoretColumn = new TableColumn<>("账户总积分");
        scoretColumn.setCellValueFactory(new PropertyValueFactory<>("scoreT"));

        TableColumn<ScoreVO, LocalDateTime> timeColumn = new TableColumn<>("时间");
        timeColumn.setCellValueFactory(new PropertyValueFactory<>("time"));

        tableView.getColumns().addAll(scoreColumn,scorevColumn,scoretColumn,timeColumn);

        // 设置布局
        VBox vbox = new VBox(tableView);
        Scene scene = new Scene(vbox, 300, 200);
        stage.setScene(scene);
        stage.show();
    }

    // 积分兑换
    @FXML
    private void buy() {
        try {
            // 加载购买页面的FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/shop/Shop.fxml"));
            Parent root = loader.load();

            // 获取购买页面的控制器实例
            ShopController shopController = loader.getController();

            // 创建新的Stage并设置Scene
            Stage stage = new Stage();
            stage.setTitle("购买页面");
            stage.setScene(new Scene(root));
            // 如果需要模态展示，可添加以下代码
            stage.initModality(Modality.APPLICATION_MODAL);

            // 展示购买页面
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 退出页面
    @FXML
    private void back() {
        Window window = backButton.getScene().getWindow();
        if (window instanceof Stage) {
            Stage stage = (Stage) window;
            stage.close(); // 关闭当前窗口
        }
    }

    public Stage getStage() {
        return stage;
    }

    public void setStage(Stage stage) {
        this.stage = stage;
    }

    public void setOff(UserInfoVO vo) {
        this.vo = vo;
    }



    private void action(Stage primaryStage, SnakePane pane){
        preStart(pane);
        SnakeCell food = new SnakeCell(190, 150, 20, Color.GREEN, "rectangle");
        pane.setFood(food);
        MoveTask task = new MoveTask(pane);

        task.setOnCancelled(event -> {
            // 在关闭主窗口会回调这里
            if (MoveTask.isForceCancel) {
                String msg = "";
                if (MoveTask.isOverBound){
                    score = (int)(pane.getScore()/10);
                    msg = "您已出界！！" + "本次得分为"+ df.format(pane.getScore())+"\n转化为"+score+"积分,存储到账户中。";
                    vo.setScore(String.valueOf(Integer.parseInt(vo.getScore())+score));
                    SpringUtil.getBean(UserInfoDao.class).UpdateByVo(vo);
                    this.saveScore(pane.getScore(), score);

                }

                if (MoveTask.isEatItSelf){
                    score = (int)(pane.getScore()/10);
                    msg = "您已经不小心把自己给吃了！！"+ "本次得分为"+ df.format(pane.getScore())+"\n转化为"+score+"积分,存储到账户中。";
                    vo.setScore(String.valueOf(Integer.parseInt(vo.getScore())+score));
                    SpringUtil.getBean(UserInfoDao.class).UpdateByVo(vo);
                    this.saveScore(pane.getScore(), score);
                }
                Alert alert = new Alert(Alert.AlertType.NONE, msg + "\n是否重新开局？",
                        new ButtonType("重新开局", ButtonBar.ButtonData.YES), new ButtonType("退出游戏", ButtonBar.ButtonData.NO));
                alert.setTitle("提示");

                Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
                stage.getIcons().add(icon);

                Optional<ButtonType> buttonType = alert.showAndWait();
                if (buttonType.isPresent()) {
                    if (buttonType.get().getButtonData().equals(ButtonBar.ButtonData.YES)) {
                        //todo 重新开局
                        MoveTask.isForceCancel = false;
                        MoveTask.reDetect();
                        action(primaryStage, pane);
                    } else {
                        //todo 退出
                        exit(task);
                        Platform.exit();
                    }
                }
            }
        });
        new Thread(task).start();

        Task<Integer> task1 = new Task<Integer>() {
            @Override
            protected Integer call() throws Exception {
                while (!isRequestClose) {
                    if (MoveTask.isEatItSelf || MoveTask.isOverBound) {
                        task.cancel(true);
                        MoveTask.isForceCancel = true;
                        break;
                    }
                }
                return null;
            }
        };
        new Thread(task1).start();

        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                exit(task);
            }
        });

    }

    private synchronized void preStart(SnakePane pane) {
        Const.SNAKE_CELL_LIST.clear();
        SnakeCell cell = new SnakeCell(50, 50, 20, Color.BLACK, "rectangle");
        SnakeCell cell1 = new SnakeCell(70, 50, 20, Color.BLACK, "rectangle");
        SnakeCell cell2 = new SnakeCell(90, 50, 20, Color.BLACK, "rectangle");

        Const.SNAKE_CELL_LIST.add(cell);
        Const.SNAKE_CELL_LIST.add(cell1);
        Const.SNAKE_CELL_LIST.add(cell2);
        pane.setScore(0);
        current_direction = Direction.R;
        pane.setSpeed(speed);
    }

    private void exit(MoveTask task) {
        isRequestClose = true;
        task.cancel();
    }


    private void saveScore(Double scorev,Integer score){
        // 保存积分记录
        ScoreVO scoreVO = new ScoreVO();
        scoreVO.setScore(scorev);
        scoreVO.setScoreV(score);
        scoreVO.setScoreT(Integer.parseInt(vo.getScore()));
        scoreVO.setVo(vo);
        scoreVO.setTime(LocalDateTime.now());
        ScoreManager.saveScore(scoreVO);
    }
}